package com.txc.cloud.admin.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.txc.cloud.admin.entity.RolePermissionEntity;
import com.txc.cloud.admin.mapper.RolePermissionMapper;
import com.txc.cloud.admin.service.IRolePermissionService;
import org.springframework.stereotype.Service;

import jakarta.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色-权限表 服务实现类
 * </p>
 *
 * @author TXC
 * @since 2023-08-02
 */
@Service
public class RolePermissionServiceImpl extends ServiceImpl<RolePermissionMapper, RolePermissionEntity> implements IRolePermissionService {

    @Resource
    private RolePermissionMapper rolePermissionMapper;


    @Override
    public void flush(Long roleId, List<String> permissionCodes) {
        List<RolePermissionEntity> rolePermissionList =
                baseMapper.selectList(Wrappers.<RolePermissionEntity>lambdaQuery().eq(RolePermissionEntity::getRoleId
                        , roleId));
        Map<Long, RolePermissionEntity> rolePermissionMap =
                rolePermissionList.stream().collect(Collectors.toMap(RolePermissionEntity::getRoleId, e -> e));
        permissionCodes.forEach(permissionCode -> {
            RolePermissionEntity roleDept = rolePermissionMap.get(roleId);
            if (ObjectUtil.isNotNull(roleDept)) {
                rolePermissionMap.remove(roleId);
            } else {
                RolePermissionEntity permissionEntity = new RolePermissionEntity();
                permissionEntity.setRoleId(roleId);
                permissionEntity.setPermissionCode(permissionCode);
                rolePermissionMapper.insert(permissionEntity);
                rolePermissionMapper.insert(permissionEntity);
            }
        });
        rolePermissionMap.forEach((k, v) -> v.deleteById());
    }

    @Override
    public void delExcludePermission(List<String> permissionCodes) {
        baseMapper.delExcludePermission(permissionCodes);
    }
}
